package com.accessibleworlds.gateway;

import java.util.Calendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.accessibleworlds.R;
import com.accessibleworlds.user.Options;
import com.accessibleworlds.user.StartPage;
import com.accessibleworlds.util.Connections;
import com.accessibleworlds.util.SharedVariables;

public class SignUp extends Activity implements OnClickListener{
	/**
	 * View elements
	 */
	private TextView title, emailTitle, emailNecessary, emailProblem, passwordTitle, passwordNecessary, passwordProblem, lastNameTitle, lastNameNecessary, lastNameProblem, firstNameTitle, firstNameNecessary, firstNameProblem, birthdayTitle, birthdayNecessary, birthdayProblem;
	private EditText emailEdit, passwordEdit, lastNameEdit, firstNameEdit;
	private DatePicker birthdayDate;
	private Button submit, cancel;
	
	private boolean isInvisible;

	private ProgressDialog progressDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		//This is for not opening keyboard at the beginning.
		if(getWindow().getAttributes().softInputMode==WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
			getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
		}

		setContentView(R.layout.signup);

		isInvisible = getIntent().getExtras().getBoolean("isInvisible");

		initializeVariables();
		changeLanguage();
		
		if(isInvisible) {
        	moveTaskToBack(true);
        }
	}

	@Override
	protected void onResume() {
		super.onResume();
		isInvisible = false;
		changeLanguage();
	}

	@Override
	protected void onPause() {
		super.onPause();
		isInvisible = true;
	}

	@Override
	public void onBackPressed() {
		Intent intent = new Intent(this,StartPage.class);
		Bundle bundle = new Bundle();
		bundle.putString("previousID", SharedVariables.signUpID);
		intent.putExtras(bundle);
		startActivity(intent);
		overridePendingTransition(R.anim.fade, R.anim.hold);
		finish();
	}

	private void initializeVariables() {
		/**
		 * Initialize view elements
		 */
		title = (TextView)findViewById(R.id.signUp);
		emailTitle = (TextView)findViewById(R.id.signUpEmailTitle);
		emailNecessary = (TextView)findViewById(R.id.signUpEmailNecessary);
		emailProblem = (TextView)findViewById(R.id.signUpEmailProblem);
		passwordTitle = (TextView)findViewById(R.id.signUpPasswordTitle);
		passwordNecessary = (TextView)findViewById(R.id.signUpPasswordNecessary);
		passwordProblem = (TextView)findViewById(R.id.signUpPasswordProblem);
		lastNameTitle = (TextView)findViewById(R.id.signUpLastNameTitle);
		lastNameNecessary = (TextView)findViewById(R.id.signUpLastNameNecessary);
		lastNameProblem = (TextView)findViewById(R.id.signUpLastNameProblem);
		firstNameTitle = (TextView)findViewById(R.id.signUpFirstNameTitle);
		firstNameNecessary = (TextView)findViewById(R.id.signUpFirstNameNecessary);
		firstNameProblem = (TextView)findViewById(R.id.signUpFirstNameProblem);
		birthdayTitle = (TextView)findViewById(R.id.signUpBirthdayTitle);
		birthdayNecessary = (TextView)findViewById(R.id.signUpBirthdayNecessary);
		birthdayProblem = (TextView)findViewById(R.id.signUpBirthdayProblem);
		
		emailEdit = (EditText)findViewById(R.id.signUpEmailEdit);
		passwordEdit = (EditText)findViewById(R.id.signUpPasswordEdit);
		lastNameEdit = (EditText)findViewById(R.id.signUpLastNameEdit);
		firstNameEdit = (EditText)findViewById(R.id.signUpFirstNameEdit);
		
		birthdayDate = (DatePicker)findViewById(R.id.signUpBirthdayDate);
		Calendar calendar = Calendar.getInstance();
		int yearInt = calendar.get(Calendar.YEAR);
		int monthInt = calendar.get(Calendar.MONTH);
		int dayInt = calendar.get(Calendar.DAY_OF_MONTH);
		birthdayDate.init(yearInt, monthInt, dayInt, null);
		
		submit = (Button)findViewById(R.id.signUpSubmit);
		cancel = (Button)findViewById(R.id.signUpCancel);
		
		submit.setOnClickListener(this);
		cancel.setOnClickListener(this);
		
		progressDialog = new ProgressDialog(this);
		progressDialog.setIndeterminate(true);
		progressDialog.setCancelable(false);
	}

	private void changeLanguage() {		
		title.setText(getResources().getStringArray(R.array.signUpUpper)[SharedVariables.currentLanguage]);
		emailTitle.setText(getResources().getStringArray(R.array.email)[SharedVariables.currentLanguage]);
		emailProblem.setText(getResources().getStringArray(R.array.emailProblem)[SharedVariables.currentLanguage]);
		passwordTitle.setText(getResources().getStringArray(R.array.password)[SharedVariables.currentLanguage]);
		passwordProblem.setText(getResources().getStringArray(R.array.passwordProblem)[SharedVariables.currentLanguage]);
		lastNameTitle.setText(getResources().getStringArray(R.array.lastName)[SharedVariables.currentLanguage]);
		lastNameProblem.setText(getResources().getStringArray(R.array.lastNameProblem)[SharedVariables.currentLanguage]);
		firstNameTitle.setText(getResources().getStringArray(R.array.firstName)[SharedVariables.currentLanguage]);
		firstNameProblem.setText(getResources().getStringArray(R.array.firstNameProblem)[SharedVariables.currentLanguage]);
		birthdayTitle.setText(getResources().getStringArray(R.array.birthday)[SharedVariables.currentLanguage]);
		birthdayProblem.setText(getResources().getStringArray(R.array.birthdayProblem)[SharedVariables.currentLanguage]);
		
		submit.setText(getResources().getStringArray(R.array.submit)[SharedVariables.currentLanguage]);
		cancel.setText(getResources().getStringArray(R.array.cancel)[SharedVariables.currentLanguage]);
		
		progressDialog.setMessage(getResources().getStringArray(R.array.signUpLoadingMessage)[SharedVariables.currentLanguage]);
	}
	
	public void onClick(View v) {
		if(v.getId() == submit.getId()) {
			//This is for hiding keyboard
			InputMethodManager imm =(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(emailEdit.getWindowToken(), 0);
			imm.hideSoftInputFromWindow(passwordEdit.getWindowToken(), 0);
			imm.hideSoftInputFromWindow(lastNameEdit.getWindowToken(), 0);
			imm.hideSoftInputFromWindow(firstNameEdit.getWindowToken(), 0);
			
			String emailString = emailEdit.getText().toString();
			String passwordString=passwordEdit.getText().toString();
			String lastNameString=lastNameEdit.getText().toString();
			String firstNameString=firstNameEdit.getText().toString();
			int dayInt = birthdayDate.getDayOfMonth();
			int monthInt = birthdayDate.getMonth();
			int yearInt = birthdayDate.getYear();
			
			new SignupTask().execute(new String[] {emailString,passwordString,lastNameString,firstNameString,yearInt+"-"+monthInt+"-"+dayInt});
		}
		else if(v.getId()==cancel.getId()){
			Intent intent = new Intent(SignUp.this,StartPage.class);
			Bundle bundle = new Bundle();
			bundle.putString("previousID", SharedVariables.signUpID);
			intent.putExtras(bundle);
			startActivity(intent);
			overridePendingTransition(R.anim.fade, R.anim.hold);
			finish();
		}
	}
	
	/**
	 * This is for checking email validation
	 * 
	 * @param emailString
	 * @return
	 */
	private boolean checkEmail(String emailString) {
		if(!(emailString.length()>0 && emailString.length()<=100))
			return false;
		
		try {
			String url = Connections.URI+Connections.checkEmail;
			String [] parameters = {"accessCode","email"};
			String [] paramaterValues = {SharedVariables.accessCode,emailString};
			
			String [] takenData = Connections.connection(url,parameters,paramaterValues);
			
			return !"Exist!!!".equalsIgnoreCase(takenData[0]);
		} catch (Exception ex) {
			return false;
		}
	}
	
	/**
	 * Validates entries such as conformity to length limits.
	 * @param passwordString The password of the user
	 * @param lastNameString Last name of the user
	 * @param firstNameString First name of the user
	 * @param birthdayString Birthday of the user in string format
	 * @return Whether the given entries conform to limits.
	 */
	private boolean checkVariablesBackground(String passwordString,String lastNameString,String firstNameString,String birthdayString) {
		boolean check = true;
		
		if(!(passwordString.length()>0 && passwordString.length()<=255))
			check = false;
		
		if(!(lastNameString.length()>0 && lastNameString.length()<=50))
			check = false;
		
		if(!(firstNameString.length()>0 && firstNameString.length()<=50))
			check = false;
		
		String tmp = birthdayString;
		int yearInt = Integer.parseInt(tmp.substring(0,tmp.indexOf("-")));
		tmp = tmp.substring(tmp.indexOf("-")+1);
		int monthInt = Integer.parseInt(tmp.substring(0,tmp.indexOf("-")));
		tmp = tmp.substring(tmp.indexOf("-")+1);
		int dayInt = Integer.parseInt(tmp);
		
		Calendar calendar = Calendar.getInstance();
		if(yearInt > calendar.get(Calendar.YEAR)) {
			check = false;
		}
		else if (yearInt == calendar.get(Calendar.YEAR)) {
			if(monthInt > calendar.get(Calendar.MONTH)) {
				check = false;
			}
			else if (monthInt == calendar.get(Calendar.MONTH)) {
				if(dayInt > calendar.get(Calendar.DAY_OF_MONTH)) {
					check = false;
				}
			}
		}
		
		return check;
	}
	
	private void checkVariables(boolean isEmailValid,String passwordString,String lastNameString,String firstNameString,String birthdayString) {
		if(!isEmailValid) {
			emailNecessary.setTextColor(getResources().getColor(R.color.red));
			emailProblem.setTextColor(getResources().getColor(R.color.red));
		}
		
		if(!(passwordString.length()>0 && passwordString.length()<=255)) {
			passwordNecessary.setTextColor(getResources().getColor(R.color.red));
			passwordProblem.setTextColor(getResources().getColor(R.color.red));
		}
		
		if(!(lastNameString.length()>0 && lastNameString.length()<=50)) {
			lastNameNecessary.setTextColor(getResources().getColor(R.color.red));
			lastNameProblem.setTextColor(getResources().getColor(R.color.red));
		}
		
		if(!(firstNameString.length()>0 && firstNameString.length()<=50)) {
			firstNameNecessary.setTextColor(getResources().getColor(R.color.red));
			firstNameProblem.setTextColor(getResources().getColor(R.color.red));
		}
		
		String tmp = birthdayString;
		int yearInt = Integer.parseInt(tmp.substring(0,tmp.indexOf("-")));
		tmp = tmp.substring(tmp.indexOf("-")+1);
		int monthInt = Integer.parseInt(tmp.substring(0,tmp.indexOf("-")));
		tmp = tmp.substring(tmp.indexOf("-")+1);
		int dayInt = Integer.parseInt(tmp);
		
		Calendar calendar = Calendar.getInstance();
		if(yearInt > calendar.get(Calendar.YEAR)) {
			birthdayNecessary.setTextColor(getResources().getColor(R.color.red));
			birthdayProblem.setTextColor(getResources().getColor(R.color.red));
		}
		else if (yearInt == calendar.get(Calendar.YEAR)) {
			if(monthInt > calendar.get(Calendar.MONTH)) {
				birthdayNecessary.setTextColor(getResources().getColor(R.color.red));
				birthdayProblem.setTextColor(getResources().getColor(R.color.red));
			}
			else if (monthInt == calendar.get(Calendar.MONTH)) {
				if(dayInt > calendar.get(Calendar.DAY_OF_MONTH)) {
					birthdayNecessary.setTextColor(getResources().getColor(R.color.red));
					birthdayProblem.setTextColor(getResources().getColor(R.color.red));
				}
			}
		}
	}
	
	private void makeDefautColor() {
		emailNecessary.setTextColor(getResources().getColor(R.color.backgroundColor));
		emailProblem.setTextColor(getResources().getColor(R.color.backgroundColor));
		passwordNecessary.setTextColor(getResources().getColor(R.color.backgroundColor));
		passwordProblem.setTextColor(getResources().getColor(R.color.backgroundColor));
		lastNameNecessary.setTextColor(getResources().getColor(R.color.backgroundColor));
		lastNameProblem.setTextColor(getResources().getColor(R.color.backgroundColor));
		firstNameNecessary.setTextColor(getResources().getColor(R.color.backgroundColor));
		firstNameProblem.setTextColor(getResources().getColor(R.color.backgroundColor));
		birthdayNecessary.setTextColor(getResources().getColor(R.color.backgroundColor));
		birthdayProblem.setTextColor(getResources().getColor(R.color.backgroundColor));
	}
	
	public class SignupTask extends AsyncTask<String, Integer, String>{
		private String emailString = "";
		private String passwordString = "";
		private String lastNameString = "";
		private String firstNameString = "";
		private String birthdayString = "";
		
		private boolean check = true;
		private boolean isEmail = true;
		
		@Override
		protected void onPreExecute(){
			progressDialog.show();
			makeDefautColor();
		}
		
		@Override
		protected String doInBackground(String... params) {
			emailString = params[0];
			passwordString = params[1];
			lastNameString = params[2];
			firstNameString = params[3];
			birthdayString = params[4];
			
			if(Connections.serviceStatus()) {
				check = checkVariablesBackground(passwordString,lastNameString,firstNameString,birthdayString);
				isEmail = checkEmail(emailString);
				
				if(check && isEmail) {
					try {
						String url = Connections.URI+Connections.signUp;
						String [] parameters = {"accessCode","email","password","lastName","firstName","birthday"};
						String [] paramaterValues = {SharedVariables.accessCode,emailString,passwordString,lastNameString,firstNameString,birthdayString};
						
						String[] results = Connections.connection(url,parameters,paramaterValues);
						
						if("OK".equalsIgnoreCase(results[0])) {
							publishProgress(2);
							return "OK";
						}
						else {
							publishProgress(3);
						}					
					} catch (Exception ex) {
						publishProgress(3);
					}
				}
				else {
					publishProgress(1);
				}
			}
			else {
				publishProgress(0);
			}
			return "Fail";
		}
		
		protected void onProgressUpdate(Integer... progress) {
			if(progress[0] == 0) {
				progressDialog.dismiss();
				AlertDialog alertDialog = new AlertDialog.Builder(SignUp.this).create();
				alertDialog.setTitle(getResources().getStringArray(R.array.connectionProblem)[SharedVariables.currentLanguage]);
				alertDialog.setMessage(getResources().getStringArray(R.array.connectionProblemException)[SharedVariables.currentLanguage]);
				alertDialog.setButton(getResources().getStringArray(R.array.tryAgain)[SharedVariables.currentLanguage], new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						new SignupTask().execute(new String [] {emailString,passwordString,lastNameString,firstNameString,birthdayString});
					}
				});
				alertDialog.setButton2(getResources().getStringArray(R.array.exit)[SharedVariables.currentLanguage], new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						finish();
					}
				});
				alertDialog.show();
			}
			else if(progress[0]==1) {
				progressDialog.dismiss();
				checkVariables(isEmail,passwordString,lastNameString,firstNameString,birthdayString);
				Toast.makeText(SignUp.this, getResources().getStringArray(R.array.parameterProblemToast)[SharedVariables.currentLanguage], Toast.LENGTH_LONG).show();
			}
			else if(progress[0]==2) {
				progressDialog.dismiss();
				Toast.makeText(SignUp.this, getResources().getStringArray(R.array.activationToast)[SharedVariables.currentLanguage], Toast.LENGTH_LONG).show();
				Intent intent = new Intent(SignUp.this,Login.class);
				Bundle bundle = new Bundle();
				bundle.putString("previousID", SharedVariables.signUpID);
				bundle.putBoolean("isInvisible", isInvisible);
				intent.putExtras(bundle);
				startActivity(intent);
				overridePendingTransition(R.anim.fade, R.anim.hold);
				finish();
			}
			else if(progress[0]==3) {
				progressDialog.dismiss();
				Toast.makeText(SignUp.this, getResources().getStringArray(R.array.connectionProblem)[SharedVariables.currentLanguage], Toast.LENGTH_LONG).show();
			}
		}
		
		@Override
		protected void onPostExecute(String result){}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater mainMenu = getMenuInflater();
		mainMenu.inflate(R.menu.mainmenu, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		menu.findItem((R.id.menuOptions)).setTitle(getResources().getStringArray(R.array.options)[SharedVariables.currentLanguage]);
		menu.findItem(R.id.menuOptions).setIcon(R.drawable.optionsicon);
		menu.findItem((R.id.menuExit)).setTitle(getResources().getStringArray(R.array.exit)[SharedVariables.currentLanguage]);
		menu.findItem((R.id.menuExit)).setIcon(R.drawable.exiticon);
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(item.getItemId()==R.id.menuOptions) {
			Intent intent = new Intent(this,Options.class);
			Bundle bundle = new Bundle();
			bundle.putString("previousID", SharedVariables.signUpID);
			intent.putExtras(bundle);
			startActivity(intent);
			overridePendingTransition(R.anim.fade, R.anim.hold);
		}
		else if (item.getItemId()==R.id.menuExit) {
			finish();
		}
		return super.onOptionsItemSelected(item);
	}
}

